<template>
  <view class="container">
		<!-- 头部 -->
		<ty-header></ty-header>
		<!-- 主体 -->
		<view class="main main-flex">
			<!-- 商品 -->
			<view class="goods">
				<!-- 商品分类 -->
				<view class="goods-tabs">
					<up-tabs :current="current" :list="typeList" @change="changeType"></up-tabs>
				</view>
				<!-- 商品搜索 -->
				<view class="goods-search">
					<uni-forms ref="searchRef" :modelValue="searchModel">
						<uni-forms-item>
							<view class="main-flex">
								<uni-easyinput placeholderStyle="font-size: 16px" v-model="searchModel.name" placeholder="请输入商品名称" />
								<view class="goods-search-btns main-flex">
									<button class="goods-search-btns-item" @click="searchSubmit">搜索</button>
									<button class="goods-search-btns-item" @click="resetSubmit">刷新</button>
								</view>
							</view>
						</uni-forms-item>
					</uni-forms>
				</view>
				<!-- 商品列表 -->
				<scroll-view scroll-y class="goods-box" @scrolltolower="scrolltolower">
					
					<!-- #ifdef APP-VUE -->
					<button style="margin: 10px; margin-top: 15rpx;" @click="open">打开副屏-显示网页</button>
					<button style="margin: 10px; margin-top: 15rpx;" @click="sndMsg">发消息到网页</button>
					<button style="margin: 10px; margin-top: 15rpx;" @click="openVideo">打开副屏-播放视频</button>
					<button style="margin: 10px; margin-top: 15rpx;" @click="cancel">取消副屏显示</button>
					<button style="margin: 10px; margin-top: 15rpx;" @click="pause">暂停播放</button>
					<button style="margin: 10px; margin-top: 15rpx;" @click="play">恢复播放</button>
					<view class="text-area">
						<text class="title">{{tip}}</text>
					</view>
					<!-- #endif -->
					
					<view class="goods-list main-flex">
						<view @click="chooseProduct(item)" class="goods-item main-flex" v-for="item in productList" :key="item.id">
							<view class="goods-item-img">
								<image class="goods-item-img-src" mode="aspectFill" lazy-load :src="item.image"></image>
							</view>
							<view class="goods-item-left main-flex">
								<view class="goods-item-name">{{item.name}}</view>
								<view class="goods-item-unit">单位：{{item.unit}}</view>
								<view class="goods-item-price">价格：￥{{item.sellPrice}}</view>
							</view>
						</view>
						<view v-if="isNull" class="goods-null main-flex"><up-empty text="商品为空"></up-empty></view>
						<view v-else class="goods-more main-flex"><uni-load-more :status="status" /></view>
					</view>
				</scroll-view>
			</view>
			<!-- 购物车 -->
			<view class="car main-flex-item">
				<view class="car-top">
					<view class="car-top-title">商品清单</view>
				</view>
				<view class="car-sell main-flex">
					<view class="car-sell-add main-flex-item" @click="openSalesman">
						<view v-if="salesmanChoose">
							<view class="car-sell-add-choose">客户姓名：{{salesmanChoose.name}}</view>
							<view class="car-sell-add-choose">客户电话：{{salesmanChoose.phone}}</view>
						</view>
						<view class="main-flex" v-else>
							<uni-icons type="plus-filled" color="#FFFFFF" size="36"></uni-icons>
							<view class="car-sell-add-text">选择销售</view>
						</view>
					</view>
					<view class="car-sell-add main-flex-item" @click="openCustomer">
						<view v-if="customerChoose">
							<view class="car-sell-add-choose">客户姓名：{{customerChoose.name}}</view>
							<view class="car-sell-add-choose">客户电话：{{customerChoose.phone}}</view>
						</view>
						<view class="main-flex" v-else>
							<uni-icons type="plus-filled" color="#FFFFFF" size="36"></uni-icons>
							<view class="car-sell-add-text">选择客户</view>
						</view>
					</view>
					<view class="car-clear main-flex" @click="clearCar">
						<uni-icons type="trash-filled" color="#FFFFFF" size="36"></uni-icons>
						<view class="car-clear-text">清空</view>
					</view>
				</view>
				<view class="car-center">
				<scroll-view scroll-y class="car-box">
					<view class="car-list">
						<view class="car-item" v-for="item in carList" :key="item.id">
							<view class="car-item-top main-flex">
								<view class="car-item-left main-flex-item">
									<view class="car-item-name">{{item.name}}</view>
								</view>
								<view class="car-item-right main-flex">
									<view class="car-item-count">
										<up-number-box v-model="item.count">
											<template #minus>
												<view class="minus">
													<uni-icons type="minus-filled" color="#32324e" size="36"></uni-icons>
													<!-- <up-icon name="minus" size="12" ></up-icon> -->
												</view>
											</template>
											<template #input>
													<view class="car-item-count-text">{{item.count}}</view>
											</template>
											<template #plus>
												<view class="plus">
													<uni-icons type="plus-filled" color="#32324e" size="36"></uni-icons>
												</view>
											</template>
										</up-number-box>
									</view>
									<uni-icons class="car-item-del" @click="delCar(item)" type="trash-filled" color="red" size="36"></uni-icons>
								</view>
							</view>
							
							<view class="car-item-bottom main-flex">
								<view class="car-item-unit main-flex-item">单位：{{item.unit}}</view>
								<view class="car-item-price main-flex-item">价格：￥{{item.sellPrice}}</view>
								<view class="car-item-money main-flex-item">合计：￥{{carProductMoney(item)}}</view>
							</view>
							
						</view>
						
						<view v-if="carList.length === 0" class="car-null main-flex"><up-empty text="商品清单为空" mode="car"></up-empty></view>
					</view>
				</scroll-view>
				</view>
				<view class="car-bottom main-flex">
					<view class="car-total main-flex">
						<view class="car-total-item">共计：{{allProductCount}}</view>
						<view class="car-total-item">合计：￥{{allProductMoney}}</view>
					</view>
					<button @click="submit" class="car-btn main-flex" :loading="isSubmit" :disabled="isSubmit">结算</button>
				</view>
			</view>
		</view>
		<!-- 底部 -->
		<ty-footer></ty-footer>
		<!-- 支付 -->
		<ty-pay
			@close="closePayment"
			@change="changePayment"
			:show="showPayment"
			:paymentList="paymentList"></ty-pay>
		<!-- 支付弹窗 -->
		<up-popup
			:show="showZfb"
			:zIndex="1000"
			closeable
			:closeOnClickOverlay="false"
			mode="center"
			@close="closeZfb"
			bgColor="transparent">
			<view class="zfb">
				<view class="zfb-title">支付中</view>
				<view class="zfb-content">
					<view class="zfb-icon">
						<image class="zfb-icon-img" src="/static/pay.gif"></image>
					</view>
					<view class="zfb-btn">
						<text class="zfb-btn-text" @click="refreshCode">刷新二维码</text>
					</view>
				</view>
			</view>
		</up-popup>
		<!-- 选择销售 -->
		<ty-salesman
			@close="closeSalesman"
			@change="changeSalesman"
			:show="showSalesman"></ty-salesman>
		<!-- 选择客户 -->
		<ty-customer
			@close="closeCustomer"
			@change="changeCustomer"
			:show="showCustomer"></ty-customer>
  </view>
</template>

<script setup>
import useUserStore from '@/store/modules/user'
import useSetStore from '@/store/modules/set.js'
import { ref, onMounted, watch, computed } from 'vue'
import { Decimal } from 'decimal.js'
import { onShow, onReady } from '@dcloudio/uni-app'
import { product, productType } from "@/api/app_api/product"
import { customer } from "@/api/app_api/user"
import { createOrder, payList, balancePay, zfbPay, zfbQuery } from "@/api/app_api/order"
import modal from '@/plugins/modal'
// #ifdef APP-VUE
	// import { openScanCode } from '@/uni_modules/cswin-sunmi-scan'
	
	// openScanCode(function (codeStr) {
	// 	// 获取扫码数据
	// 	console.log(codeStr)
	// })
// #endif
	// 商品分类
	const typeList = ref([])
	
	const getAllType = () => {
		productType().then(res => {
			typeList.value = [{
				name: '全部商品',
				id: ''
			}].concat(res.data) || []
		})
	}
	
	// 选择商品分类
	const current = ref(0)
	const changeType = (e) => {
		current.value = e.index ? e.index : 0
		searchModel.value.typeId = e.id ? e.id : ''
		searchModel.value.name = ''
		searchFirst()
	}
	
	// 获取商品数据
	const productList = ref([])
	const pageNum = ref(1)
	const pageSize = ref(18)
	const total = ref(0)
	const isLoading = ref(false)
	const status = ref('more')
	const isNull = ref(false)
	
	// 确认搜索
	const searchRef = ref(null)
	const searchModel = ref({
		name: '',
		typeId: ''
	})
	const searchSubmit = () => {
		pageNum.value = 1
		searchModel.value.typeId = ''
		current.value = 0
		searchFirst()
	}
	// 重置搜索
	const resetSubmit = () => {
		searchModel.value = {
			name: '',
			typeId: ''
		}
		current.value = 0
		searchFirst()
	}
	
	const searchFirst = () => {
		pageNum.value = 1
		productList.value = []
		getList()
	}
	
	const getList = () => {
		const params = {
			sellChannel: 4
		}
		if (searchModel.value.name) {
			params.productName = searchModel.value.name
		}
		if (searchModel.value.typeId) {
			params.typeId = searchModel.value.typeId
			params.regionCode = userStore.user.regionCode
		} else {
			params.pageNum = pageNum.value
			params.pageSize = pageSize.value
		}
		isLoading.value = true
		// uni.showLoading({
		// 	title: '数据加载中...'
		// })
		product(params).then(res => {
			if (params.typeId) {
				productList.value = res.data.reduce((acc, curr) => acc.concat(curr.productList), [])
				status.value = 'no-more'
				total.value = productList.value.length
				isNull.value = total.value === 0 && pageNum.value === 1
			} else {
				productList.value = productList.value.concat(res.data || [])
				status.value = res.data.length === pageSize.value ? 'loading' : 'no-more'
				total.value = res.allNumber
				isNull.value = res.allNumber === 0 && pageNum.value === 1
			}
			isLoading.value = false
			// uni.hideLoading()
		}).catch(() => {
			isLoading.value = false
			// uni.hideLoading()
		})
	}
	
	// 触底
	const scrolltolower = () => {
		if(status.value == 'no-more') return false;
		pageNum.value += 1
		status.value = 'loading'
		getList()
	}
	
	// 选择商品
	const chooseProduct = (product) => {
		const carFilter = carList.value.filter(item => item.id === product.id)
		if (carFilter.length === 0) {
			carList.value.push({
				...product,
				count: 1
			})
		}
	}
	// 删除商品
	const delCar = (product) => {
		carList.value = carList.value.filter(item => item.id !== product.id)
	}
	// 购物车
	const carList = ref([])
	
	// 单个商品计算
	const carProductMoney = computed(() => {
		return (item) => {
			return (Decimal(item.count).mul(Decimal(item.sellPrice)).toNumber()).toFixed(2)
		}
	})
	
	// 合计
	const allProductMoney = computed(() => {
		let allMoney = 0
		if (carList.value.length > 0) {
			allMoney = carList.value.reduce((prev, cur, index, arr)=> {
				const oneMoney = cur.count ? Decimal(cur.count).mul(Decimal(cur.sellPrice)) : 0
				return Decimal(prev).add(oneMoney).toNumber()
			}, 0)
		}
		return allMoney.toFixed(2)
	})
	const allProductCount = computed(() => {
		let allCount = 0
		if (carList.value.length > 0) {
			allCount = carList.value.reduce((prev, cur, index, arr)=> {
				return prev + cur.count
			}, 0)
		}
		return allCount
	})
	
	// 结算
	const isSubmit = ref(false)
	const submit = async () => {
		if (carList.value.length === 0) {
			modal.alert('请选择商品')
			return false
		}
		const productList = carList.value.map(item => {
			return {
				moreSpec: item.moreSpec,
				number: item.count,
				price: item.sellPrice,
				productId: item.id,
				productImg: item.image,
				productName: item.name,
				productSpecId: '',
				productSpecName: '',
				unit: item.unit,
				sellChannel: 4
			}
		})
		const params = {
			productList,
			couponList: [],
			couponProductList: [],
			customerAddrId: userStore.customerAddrId,
			regionCode: userStore.user.regionCode,
			remark: '',
			sellChannel: 4
		}
		if (salesmanChoose.value) {
			const salesmanConfirm = modal.confirm(`确认销售为${salesmanChoose.value.name}`)
			if (!salesmanConfirm) {
				return false
			}
			params.salesmanId = salesmanChoose.value.id
		}
		if (customerChoose.value) {
			const customerConfirm = await modal.confirm(`确认客户为${customerChoose.value.name}`)
			if (!customerConfirm) {
				return false
			}
			params.customerId = customerChoose.value.id
		}
		isSubmit.value = true
		createOrder(params).then(res => {
			isSubmit.value = false
			if (res.data.id) {
				openPayment(res.data)
			}
			// uni.hideLoading()
		}).catch((err) => {
			isSubmit.value = false
			// uni.hideLoading()
		})
	}
	
	// 清空商品
	const clearCar = () => {
		carList.value = []
		salesmanChoose.value = null
		customerChoose.value = null
	}
	
	// 去支付
	const showPayment = ref(false)
	const orderNumber = ref('')
	const orderId = ref('')
	const paymentId = ref('')
	const openPayment = (res) => {
		showPayment.value = true
		orderNumber.value = res.orderNumber
		orderId.value = res.id
	}
	// 获取支付方式
	const paymentList = ref([])
	const getPayList = () => {
		payList().then(res => {
			paymentList.value = res.data
		})
	}
	// 关闭支付方式
	const closePayment = () => {
		showPayment.value = false
		orderNumber.value = ''
		orderId.value = ''
	}
	// 选择支付方式
	const changePayment = (res) => {
		if (!orderNumber.value || !orderId.value) {
			modal.alert('获取订单失败')
			return false
		}
		if (res.id === 2) { // 余额支付
			getBalancePay(orderId.value)
		} else if (res.id === 6) { // 支付宝扫码
			getZfbPay(orderNumber.value, res.id)
		} else {
			modal.alert('暂不支持该支付方式')
		}
	}
	// 余额支付
	const isPay = ref(false)
	const getBalancePay = (orderId) => {
		if (isPay.value) return false
		isPay.value = true
		balancePay({
			id: orderId
		}).then(res => {
			uni.showModal({
			  content: '支付成功',
			  confirmText: '确定',
				showCancel: false,
			  success: function (res) {
			    if (res.confirm) {
			      isPay.value = false
			      paySuccess()
			    }
			  }
			})
		}).catch((err) => {
			isPay.value = false
		})
	}
	
	// 支付宝扫码
	const payUrl = ref('')
	const getZfbPay = (orderNumber, paymentId) => {
		if (isPay.value) return false
		isPay.value = true
		zfbPay({
			orderNumber,
			paymentId
		}).then(res => {
			if (res.msg) {
				payUrl.value = res.msg
				window.open(res.msg)
				payZfbSuccess(orderNumber)
			}
		}).catch((err) => {
			isPay.value = false
		})
	}
	
	const timer = ref(null)
	const timerCount = ref(0)
	
	// 判断扫码支付
	const showZfb = ref(false)
	const payZfbSuccess = (orderNumber) => {
		showZfb.value = true
		timerCount.value = 0
		clearInterval(timer.value)
		timer.value = setInterval(() => {
			zfbQuery({
				orderNumber
			}).then(res => {
				timerCount.value ++
				if (res.code === 200) {
					closeZfb()
					paySuccess()
				}
			}).catch(() => {
				closeZfb()
			})
		}, 3000)
		
	}
	const closeZfb = () => {
		payUrl.value = ''
		isPay.value = false
		clearInterval(timer.value)
		showZfb.value = false
	}
	const refreshCode = () => {
		if (payUrl.value) {
			window.open(payUrl.value)
			payZfbSuccess(orderNumber.value)
		}
	}
	
	// 支付成功
	const paySuccess = () => {
		userStore.getInfo()
		clearCar()
		closePayment()
	}
	
	// 选择销售
	const showSalesman = ref(false)
	const salesmanChoose = ref(null)
	const openSalesman = () => {
		showSalesman.value = true
	}
	const closeSalesman = () => {
		showSalesman.value = false
	}
	const changeSalesman = (item) => {
		salesmanChoose.value = item
		showSalesman.value = false
	}
	
	// 选择客户
	const showCustomer = ref(false)
	const customerChoose = ref(null)
	const openCustomer = () => {
		showCustomer.value = true
	}
	const closeCustomer = () => {
		showCustomer.value = false
	}
	const changeCustomer = (item) => {
		customerChoose.value = item
		showCustomer.value = false
	}
	
	
	
	
	const tip = ref('')
	const userStore = useUserStore()
	const setStore = useSetStore()
	// #ifdef APP-VUE
	const plug = uni.requireNativePlugin("Html5app-TwoDisplay")
	const open = () => {
		let num=Math.ceil(Math.random()*100)
		plug.showWebUrl({url:"web/index.html?id="+num},ret=>{
			 tip.value = JSON.stringify(ret)
		})
	}
	const openVideo = () => {
		
		// let videoPath = plus.io.convertLocalFileSystemURL("static/video_171129.mp4"); //如果是本地视频，路径需要转换成平台绝对路径
		
		plug.setVideoListPlay({
		mute:true, //播放视频时，是否静音
		videolist: //视频链接
		[ 
		"https://onehk-1251146759.cos.ap-guangzhou.myqcloud.com/2017123101.mp4" //网络视频
		]
		},ret=>{
			
			 tip.value=JSON.stringify(ret);
			
		})
	}
	const cancel = () => {
		plug.cancel()
	}
	const play = () => {
		plug.play()
	}
	const pause = () => {
		plug.pause()
	}
	const sndMsg = () => {
		let num=Math.ceil(Math.random()*100);  //随机数
		plug.sndMsgToHtml({data:num})
	}
	// #endif 
	onShow(() => {
		
	})
	
	onMounted(() => {
		getAllType()
		searchFirst()
		getPayList()
	})
	onReady(() => {
	})
</script>

<style scoped lang="scss">
	.container {
		width: 100%;
		height: 100vh;
		.main {
			height: calc(100vh - 100px);
			padding: 10px;
			align-items: flex-start;
		}
		.goods {
			width: 980px;
			height: 100%;
			background-color: #ffffff;
			border-radius: 10px;
			padding: 10px 20px;
			&-search {
				margin-top: 10px;
				:deep(.uni-easyinput__content-input) {
					height: 42px;
					font-size: 16px;
				}
				&-placeholder {
					font-size: 16px;
				}
				&-btns {
					&-item {
						display: flex;
						width: 120px;
						height: 42px;
						align-items: center;
						justify-content: center;
						background-color: #32324e;
						border-color: #32324e;
						color: #ffffff;
						margin-left: 20px;
					}
				}
			}
			&-box {
				height: calc(100vh - 258px);
			}
			&-list {
				flex-wrap: wrap;
			}
			&-item {
				width: 300px;
				height: 120px;
				border: 1px solid #42425e;
				border-radius: 5px;
				margin-bottom: 20px;
				margin-left: 20px;
				overflow: hidden;
				cursor: pointer;
				&:nth-child(3n+1) {
					margin-left: 0px;
				}
				&-img {
					width: 120px;
					height: 120px;
					&-src {
						width: 120px;
						height: 120px;
					}
				}
				&-left {
					height: 100%;
					flex-direction: column;
					align-items: flex-start;
					justify-content: space-between;
					padding: 10px;
				}
				&-name {
					font-weight: 600;
					font-size: 15px;
				}
				&-unit {
					font-size: 14px;
				}
				&-price {
					font-weight: 600;
					font-size: 16px;
					color: red;
				}
			}
			&-null {
				width: 100%;
				justify-content: center;
				padding: 40px;
			}
			&-more {
				width: 100%;
				justify-content: center;
			}
		}
		.car {
			// width: 50%;
			height: 100%;
			margin-left: 10px;
			background-color: #ffffff;
			border-radius: 5px;
			overflow: hidden;
			&-top {
				padding: 0 10px;
				&-title {
					font-size: 24px;
					font-weight: bold;
					line-height: 60px;
				}
			}
			&-sell {
				height: 60px;
				padding: 0 10px;
				background-color: #42425e;
				&-add {
					font-size: 20px;
					font-weight: 600;
					cursor: pointer;
					color: #ffffff;
					&-text {
						margin-left: 10px;
					}
					&-choose {
						font-size: 14px;
					}
				}
			}
			&-clear {
				font-size: 20px;
				font-weight: 600;
				cursor: pointer;
				color: #ffffff;
				margin-left: auto;
				&-text {
					margin-left: 10px;
				}
			}
			&-center {
				padding: 20px 0;
			}
			&-box {
				width: 100%;
				height: calc(100vh - 260px - 120px);/*60px - 56px - 40px - 100px*/
				padding: 0 10px;
			}
			&-bottom {
				width: 100%;
				height: 100px;
			}
			&-item {
				align-items: flex-start;
				padding: 10px;
				background-color: #f6f6f6;
				border-radius: 5px;
				&+.car-item {
					margin-top: 10px;
				}
				&-right {
					margin-left: auto;
				}
				&-name {
					font-weight: 800;
					font-size: 18px;
				}
				&-count {
					padding: 0 20px;
					&-text {
						width: 40px;
						font-size: 20px;
						text-align: center;
					}
				}
				&-bottom {
					margin-top: 10px;
					font-weight: 600;
					font-size: 16px;
				}
				&-price {
					color: red;
				}
				&-money {
					color: red;
					text-align: right;
				}
				&-del {
					cursor: pointer;
				}
			}
			&-bottom {
				padding-left: 10px;
				background-color: #32324e;
			}
			&-null {
				width: 100%;
				justify-content: center;
				padding: 40px;
			}
			&-total {
				font-size: 20px;
				font-weight: 600;
				color: #ffffff;
				&-item {
					&+.car-total-item {
						margin-left: 20px;
					}
				}
			}
			&-btn {
				width: 200px;
				height: 100%;
				font-size: 40px;
				font-weight: bold;
				justify-content: center;
				background-color: red;
				color: #ffffff;
				margin: 0;
				margin-left: auto;
				text-align: center;
				cursor: pointer;
				padding: 0;
				border-radius: 0px;
			}
		}
	}
	.zfb {
		width: 480px;
		border-radius: 10px;
		background-color: #ffffff;
		&-title {
			line-height: 48px;
			text-align: center;
			font-weight: 600;
			font-size: 20px;
		}
		&-content {
			padding: 40px;
		}
		&-icon {
			text-align: center;
			&-img {
				width: 200px;
				height: 200px;
			}
		}
		&-btn {
			margin-top: 20px;
			font-size: 18px;
			font-weight: 600;
			text-align: center;
			&-text {
				cursor: pointer;
			}
		}
	}
</style>
